<template>
  <div class="edit-address back-page">
    <HeaderTop>
      <template #left>
        <van-icon
          name="arrow-left"
          @click="router.back()"
          size="20"
          style="transform: translateX(-0.3rem)"
        />
      </template>
      <template #center>
        <div class="fs-1 wd-75 center strong" style="color: white">编辑地址</div>
      </template>
      <template #right>
        <div class="fs-4 wd-75 center" style="color: white" @click="deleteIsShow = !deleteIsShow">
          编辑
        </div>
      </template>
    </HeaderTop>
    <div class="address py-3">
      <van-cell-group inset>
        <van-cell
          v-for="add in addressList"
          :key="add.id"
          :title="`${add.name} ${add.phone} `"
          :label="add.address + add.address_detail"
          center
        >
          <template #right-icon>
            <van-icon name="delete-o" @click="deleteAddress(add.id)" v-show="deleteIsShow" />
          </template>
        </van-cell>
      </van-cell-group>
    </div>
    <div class="add-address-btn">
      <van-button round block type="primary" icon="plus" :to="{ name: 'AddAddress' }">
        添加地址
      </van-button>
    </div>
    <router-view v-slot="{ Component }">
      <transition name="detail-show">
        <component :is="Component" />
      </transition>
    </router-view>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { getMyAddress, deleteMyAddress } from "@/api";
import { UserAddress_format, successInfo_format } from "@/type/index";
import { user } from "@/store/index";
import { storeToRefs } from "pinia";
import { Dialog, Toast } from "vant";
const router = useRouter();
const store = user();
const { user_id } = storeToRefs(store);
//获取个人收货地址列表
const addressList = ref<UserAddress_format[]>();
const getAddress = async () => {
  const res = await getMyAddress<UserAddress_format[]>(user_id.value);
  addressList.value = res;
  console.log(res);
};
//是否显示删除按钮
const deleteIsShow = ref<boolean>(false);
//点击删除地址按钮
const deleteAddress = id => {
  Dialog.confirm({
    title: "提示",
    message: "是否删除该地址",
  }).then(async () => {
    const res = await deleteMyAddress<successInfo_format>(user_id.value, id);
    if (res.status === 1) {
      getAddress();
      Toast.success("删除成功");
    } else {
      Toast.fail("删除失败");
    }
  }).catch(()=>{
    console.log('取消删除')
  });
};
//初始化函数
const initData = () => {
  getAddress();
}
//调用初始化函数
initData()
</script>

<style lang="scss" scoped>
.edit-address {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 21;
  overflow-x: hidden;
  display: flex;
  flex-direction: column;
  .address {
    flex: 1;
    height: 0;
    overflow-y: auto;
  }
  .add-address-btn{
    margin: 16px;
  }
}
</style>
